<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门" prop="department">
        <el-select v-model="queryParams.department" placeholder="请选择部门" clearable size="small">
          <el-option
            v-for="dict in departmentOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入用户名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工号" prop="staffNum">
        <el-input
          v-model="queryParams.staffNum"
          placeholder="请输入工号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="余额" prop="balance">
        <el-input
          v-model="queryParams.balance"
          placeholder="请输入余额"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否删除" prop="deleted">
        <el-select v-model="queryParams.deleted" placeholder="请选择是否删除" clearable size="small">
          <el-option
            v-for="dict in deletedOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['user:userManage:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['user:userManage:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['user:userManage:remove']"
        >删除
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['user:userManage:export']"
        >导出
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-menu"
          size="mini"
          @click="handleRecharge"
          v-hasPermi="['user:userManage:recharge']"
        >批量充值优惠卷
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-upload
          class="upload-demo"
          :action="importUrl"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :on-success="uploadSuccess"
          :on-error="uploadFail"
          multiple
          name="staffFile"
          :limit="200"
          :on-exceed="handleExceed"
          :file-list="fileList">
          <el-button size="small" type="primary">员工导入Excel上传</el-button>
        </el-upload>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userManageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="用户id" align="center" prop="id"/>
      <el-table-column label="电话" align="center" prop="phone"/>
      <el-table-column label="部门" align="center" prop="department" :formatter="departmentFormat"/>
      <el-table-column label="用户名" align="center" prop="name"/>
      <el-table-column label="工号" align="center" prop="staffNum"/>
      <el-table-column label="余额" align="center" prop="balance"/>
      <el-table-column label="是否删除" align="center" prop="deleted" :formatter="deletedFormat"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['user:userManage:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['user:userManage:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话"/>
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select v-model="form.department" placeholder="请选择部门">
            <el-option
              v-for="dict in departmentOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="name">
          <el-input v-model="form.name" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="工号" prop="staffNum">
          <el-input v-model="form.staffNum" placeholder="请输入工号"/>
        </el-form-item>
        <el-form-item label="余额" prop="balance">
          <el-input v-model="form.balance" placeholder="请输入余额"/>
        </el-form-item>
        <el-form-item label="是否删除" prop="deleted">
          <el-select v-model="form.deleted" placeholder="请选择是否删除">
            <el-option
              v-for="dict in deletedOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- RechargeForm批量充值对话框 -->
    <el-dialog
      title="批量充值优惠卷"
      :visible.sync="dialogRechargeFormVisible"
      width="30%"
      :before-close="handleClose">
      <template slot-scope="scope">

        <el-form :model="rechargeForm" :rules="rechargeForm_rules">
          <el-form-item label="优惠卷数量" label-width="100px">
            <el-input v-model="rechargeForm.amount" autocomplete="off" style="width: 218px"></el-input>
          </el-form-item>
          <el-form-item label="优惠卷金额值" label-width="100px">
            <el-select v-model="rechargeForm.discount" placeholder="请选择优惠卷金额">
              <el-option label="10元折扣" value="10"></el-option>
              <el-option label="50元折扣" value="50"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
      <el-button @click="dialogRechargeFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="rechargeFormSubmit(scope.row)">确 定</el-button>
      </span>
      </template>

    </el-dialog>

  </div>
</template>

<script>
  import {
    listUserManage,
    getUserManage,
    delUserManage,
    addUserManage,
    updateUserManage,
    exportUserManage,
    rechargeCoupon
  } from "@/api/user/userManage";

  export default {
    name: "UserManage",
    components: {},
    data() {
      return {
        //导入的员工文件列表
        fileList: [],

        //导入请求的url
        importUrl:process.env.VUE_APP_BASE_API+"/user/userManage/import",

        //批量充值表单
        dialogRechargeFormVisible: false,

        //充值金额表单
        rechargeForm: {
          amount: 0,
          discount: 0
        },

        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 用户管理表格数据
        userManageList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 部门字典
        departmentOptions: [],
        // 是否删除字典
        deletedOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          phone: null,
          department: null,
          name: null,
          staffNum: null,
          balance: null,
          deleted: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          phone: [
            {required: true, message: "电话不能为空", trigger: "blur"}
          ],
          department: [
            {required: true, message: "部门不能为空", trigger: "change"}
          ],
          name: [
            {required: true, message: "用户名不能为空", trigger: "blur"}
          ],
          balance: [
            {required: true, message: "余额不能为空", trigger: "blur"}
          ],
          createTime: [
            {required: true, message: "创建时间不能为空", trigger: "blur"}
          ],
          updateTime: [
            {required: true, message: "更新时间不能为空", trigger: "blur"}
          ],
          deleted: [
            {required: true, message: "是否删除不能为空", trigger: "change"}
          ]
        },

        //充值金额表单校验
        rechargeForm_rules: {
          amount: [
            {required: true, message: "充值数量不能为空", trigger: "blur"}
          ],
          discount: [
            {required: true, message: "充值折扣数不能为空", trigger: "change"}
          ]
        }

      };
    },
    created() {
      this.getList();
      this.getDicts("department").then(response => {
        this.departmentOptions = response.data;
      });
      this.getDicts("is_deleted").then(response => {
        this.deletedOptions = response.data;
      });
    },
    methods: {
      /** 导入员工excel文件 */
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      uploadSuccess(){
        this.$message({
          showClose: true,
          message: '导入成功',
          type: 'success'
        });
      },
      uploadFail(){
        this.$message({
          showClose: true,
          message: '导入失败',
          type: 'error'
        });
      },
      /** 查询用户管理列表 */
      getList() {
        this.loading = true;
        listUserManage(this.queryParams).then(response => {
          this.userManageList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 部门字典翻译
      departmentFormat(row, column) {
        return this.selectDictLabel(this.departmentOptions, row.department);
      },
      // 是否删除字典翻译
      deletedFormat(row, column) {
        return this.selectDictLabel(this.deletedOptions, row.deleted);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          phone: null,
          department: null,
          name: null,
          staffNum: null,
          balance: null,
          createTime: null,
          updateTime: null,
          deleted: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加用户管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getUserManage(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改用户管理";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateUserManage(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addUserManage(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除用户管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delUserManage(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有用户管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportUserManage(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        })
      },
      /** 批量充值按钮操作 */
      handleRecharge() {
        console.log("进入充值按钮功能");
        this.dialogRechargeFormVisible = true;


      },

      /**管理批量充值关闭之前的确认 */
      handleClose(done) {
        this.$confirm('确认关闭?')
          .then(_ => {
            done();
          }).catch(_ => {

        })
      },

      /** 批量充值提交 */
      rechargeFormSubmit() {

        //获取选中的用户id
        const ids = this.ids;

        console.log("选中的ids"+ids)

        let data = {
          "ids":ids,
          amount:Number(this.rechargeForm.amount),
          discount:Number(this.rechargeForm.discount)
        };

        console.log("构建的data数据"+JSON.stringify(data))




        rechargeCoupon(data).then(response => {
          alert(JSON.stringify(res));
        });

        // 关闭弹窗
        this.dialogRechargeFormVisible = false;

      }


    }
  };
</script>
